package top.broncho.gank.ui.activity

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import top.broncho.gank.R
import top.broncho.gank.bean.LoginData
import top.broncho.gank.constant.Constant
import top.broncho.gank.databinding.ActivityLoginBinding
import top.broncho.gank.ext.showToast
import top.broncho.gank.utils.DialogUtil
import top.broncho.gank.utils.Preference
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.android.synthetic.main.toolbar.*
import org.jetbrains.anko.info
import org.jetbrains.anko.warn
import top.broncho.mvvm.base.BaseVMActivity

class LoginActivity : BaseVMActivity<ActivityLoginBinding>() {
    private val viewModel by viewModels<LoginViewModel> { viewModelFactory }

    /**
     * local username
     */
    private var user: String by Preference(Constant.USERNAME_KEY, "")

    /**
     * local password
     */
    private var pwd: String by Preference(Constant.PASSWORD_KEY, "")

    /**
     * token
     */
    private var token: String by Preference(Constant.TOKEN_KEY, "")


    private val mDialog by lazy {
        DialogUtil.getWaitDialog(this, getString(R.string.login_ing))
    }

    fun showLoading() {
        mDialog.show()
    }

    fun hideLoading() {
        mDialog.dismiss()
    }

    override fun getLayoutId(): Int = R.layout.activity_login

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initView()
        viewModel.login.observe({ lifecycle }) {
            if (it.isFailure) {
                warn { "login failed:${it.exceptionOrNull()}" }
                return@observe
            }
            loginSuccess(it.getOrThrow())
        }
    }

    fun initView() {
        et_username.setText(user)
        toolbar.run {
            title = resources.getString(R.string.login)
            setSupportActionBar(this)
            supportActionBar?.setDisplayHomeAsUpEnabled(true)
        }
        btn_login.setOnClickListener(onClickListener)
        tv_sign_up.setOnClickListener(onClickListener)
    }


    fun loginSuccess(data: LoginData) {
        showToast(getString(R.string.login_success))
        isLogin = true
        user = data.username
        pwd = data.password
        token = data.token

        info { "loginSuccess: $data" }
        setResult(Activity.RESULT_OK)
        finish()
    }

    /**
     * OnClickListener
     */
    private val onClickListener = View.OnClickListener { view ->
        when (view.id) {
            R.id.btn_login -> {
                login()
            }
            R.id.tv_sign_up -> {
                val intent = Intent(this@LoginActivity, RegisterActivity::class.java)
                startActivity(intent)
                finish()
                overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
            }
        }
    }

    /**
     * Login
     */
    private fun login() {
        if (validate()) {
            viewModel.loginWanAndroid(et_username.text.toString(), et_password.text.toString())
        }
    }

    /**
     * Check UserName and PassWord
     */
    private fun validate(): Boolean {
        var valid = true
        val username: String = et_username.text.toString()
        val password: String = et_password.text.toString()

        if (username.isEmpty()) {
            et_username.error = getString(R.string.username_not_empty)
            valid = false
        }
        if (password.isEmpty()) {
            et_password.error = getString(R.string.password_not_empty)
            valid = false
        }
        return valid
    }

}
